package org.datastructure.firstday.huffmancode;

import java.io.*;
import java.util.*;

public class HuffmanCode {

    static Map<Byte, String> huffmanMap = new HashMap<>();
    static StringBuilder stringBuilder = new StringBuilder();

    public static void main(String[] args) {
        String content = "i like like like java do you like a java";
        byte[] bytes = content.getBytes();
/*
        List<Node> nodes = getNodes(bytes);
        System.out.println(nodes);
        Node root = createHuffmanTree(nodes);
        root.preOrder();
        getCode(root); 
        System.out.println(huffmanMap);
        byte[] zip = zip(bytes);
        System.out.println(Arrays.toString(zip));
*/

        byte[] huffmanCodeBytes = HuffmanZip(bytes);
        // System.out.println(Arrays.toString(huffmanCodeBytes));
        byte[] decode = decode(huffmanMap, huffmanCodeBytes);
        //  System.out.println(new String(decode));


      //zipFile("C:\\Users\\admin\\Desktop\\MusicDownload\\阿衣莫 - 阿吉太组合.mp3", "C:\\Users\\admin\\Desktop\\新建文件夹\\src.zip");
        //   System.out.println("压缩完成");

     unzipFile("C:\\Users\\admin\\Desktop\\新建文件夹\\src.zip", "C:\\Users\\admin\\Desktop\\MusicDownload\\阿衣莫 - 阿吉太组合123.mp3");

    }

    public static void unzipFile(String zipFile, String targetFile) {
        ObjectInputStream ois = null;
        FileInputStream fis = null;
        FileOutputStream fos = null;

        try {
            fis = new FileInputStream(zipFile);
            ois = new ObjectInputStream(fis);
            byte[] huffmanCodeBytes = (byte[]) ois.readObject();
            Map<Byte, String> huffmanTable = (Map<Byte, String>) ois.readObject();
            byte[] decode = decode(huffmanTable, huffmanCodeBytes);
            fos = new FileOutputStream(targetFile);
            fos.write(decode);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                ois.close();
                fis.close();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 使用Huffman 编码方式压缩文件
     *
     * @param filePath
     * @param targetFile
     */
    public static void zipFile(String filePath, String targetFile) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;

        try {
            fis = new FileInputStream(filePath);
            byte[] bytes = new byte[fis.available()];
            fis.read(bytes);
            byte[] huffmanCodeBytes = HuffmanZip(bytes);
            fos = new FileOutputStream(targetFile);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(huffmanCodeBytes);
            oos.writeObject(huffmanMap);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                fis.close();
                fos.close();
                oos.close();
            } catch (Exception ee) {

            }
        }
    }

    private static byte[] decode(Map<Byte, String> huffmanCodes, byte[] huffmanBytes) {

        //1. 先得到 huffmanBytes 对应的 二进制的字符串 ， 形式 1010100010111...
        StringBuilder stringBuilder = new StringBuilder();
        //将byte数组转成二进制的字符串
        for (int i = 0; i < huffmanBytes.length; i++) {
            byte b = huffmanBytes[i];
            //判断是不是最后一个字节
            boolean flag = (i == huffmanBytes.length - 1);
            stringBuilder.append(byteToBitString(!flag, b));
        }
        //把字符串安装指定的赫夫曼编码进行解码
        //把赫夫曼编码表进行调换，因为反向查询 a->100 100->a
        Map<String, Byte> map = new HashMap<String, Byte>();
        for (Map.Entry<Byte, String> entry : huffmanCodes.entrySet()) {
            map.put(entry.getValue(), entry.getKey());
        }

        //创建要给集合，存放byte
        List<Byte> list = new ArrayList<>();
        //i 可以理解成就是索引,扫描 stringBuilder
        for (int i = 0; i < stringBuilder.length(); ) {
            int count = 1; // 小的计数器
            boolean flag = true;
            Byte b = null;

            while (flag) {
                //1010100010111...
                //递增的取出 key 1
                String key = stringBuilder.substring(i, i + count);//i 不动，让count移动，指定匹配到一个字符
                b = map.get(key);
                if (b == null) {//说明没有匹配到
                    count++;
                } else {
                    //匹配到
                    flag = false;
                }
            }
            list.add(b);
            i += count;//i 直接移动到 count
        }
        //当for循环结束后，我们list中就存放了所有的字符  "i like like like java do you like a java"
        //把list 中的数据放入到byte[] 并返回
        byte b[] = new byte[list.size()];
        for (int i = 0; i < b.length; i++) {
            b[i] = list.get(i);
        }
        return b;

    }

    /*
     */

    /**
     * huffman 解码
     *
     * @return
     *//*

    public static byte[] decode(Map<Byte, String> huffmanMap, byte[] huffmanCodeBytes) {
        // TODO: 2022/1/12  将huffman code 转为二进制码并拼接 
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < huffmanCodeBytes.length; i++) {
            boolean flag = (i == huffmanCodeBytes.length - 1);
            stringBuilder.append(byteToBitString(!flag, huffmanCodeBytes[i]));
        }
        // System.out.println(stringBuilder.toString());
        // TODO: 2022/1/12 根据huffmanMap表值解码

        // TODO: 2022/1/12 将huffmanMap 表key和value反转
        HashMap<String, Byte> huffmanTable = new HashMap<>(huffmanMap.size());
        huffmanMap.forEach((k, v) -> {
            huffmanTable.put(v, k);
        });

        // TODO: 2022/1/12  根据huffman表，依次查找
        ArrayList<Byte> lists = new ArrayList<>();
        //创建要给集合，存放byte
        List<Byte> list = new ArrayList<>();
        //i 可以理解成就是索引,扫描 stringBuilder
        for(int  i = 0; i < stringBuilder.length(); ) {
            int count = 0; // 小的计数器
            boolean flag = true;
            Byte b = null;

            while(flag) {
                //1010100010111...
                //递增的取出 key 1
                String key = stringBuilder.substring(i, i+count);//i 不动，让count移动，指定匹配到一个字符
                b = huffmanTable.get(key);
                if(b == null) {//说明没有匹配到
                    count++;
                }else {
                    //匹配到
                    flag = false;
                }
            }
            list.add(b);
            i += count;//i 直接移动到 count
        }
        //System.out.println(lists.size());
        byte[] bytes = new byte[lists.size()];
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = lists.get(i);
        }

        return bytes;
    }
*/
    public static String byteToBitString(boolean flag, byte b) {

        // TODO: 2022/1/12  如果是正数，需要通过位于运算补位，且将byte转为包含256值的类型，如short char int 。。。 都行
        short stemp = b;
        if (flag) {
            stemp |= 256;
        }
        String str = Integer.toBinaryString(stemp);
        // TODO: 2022/1/12 需要判断如果是huffman code bytes 尾，则不需要截取和补位
        if (flag) {
            return str.substring(str.length() - 8);
        } else {
            return str;
        }
    }

    /**
     * 酱紫届满压缩成霍夫曼字节码
     *
     * @param bytes
     * @return
     */
    public static byte[] HuffmanZip(byte[] bytes) {
        List<Node> nodes = getNodes(bytes);
        Node root = createHuffmanTree(nodes);
        Map<Byte, String> huffman = getCode(root);
        return zip(bytes);
    }

    /**
     * 将Huffman字节码压缩
     *
     * @param bytes
     * @return
     */
    public static byte[] zip(byte[] bytes) {
        StringBuilder stringBuilder = new StringBuilder();
        for (Byte b : bytes) {
            stringBuilder.append(huffmanMap.get(b));
        }

        // System.out.println(stringBuilder.toString());
        int len;
        if (stringBuilder.length() / 8 == 0) {
            len = stringBuilder.length() / 8;
        } else {
            len = stringBuilder.length() / 8 + 1;
        }

        byte[] heffmanCodeBytes = new byte[len];
        int index = 0;
        for (int i = 0; i < stringBuilder.length(); i += 8) {
            String strByte;
            if (i + 8 < stringBuilder.length()) {
                strByte = stringBuilder.substring(i, i + 8);
            } else {
                strByte = stringBuilder.substring(i);
            }

            heffmanCodeBytes[index++] = (byte) Integer.parseInt(strByte, 2);
        }
        return heffmanCodeBytes;
    }


    public static Map<Byte, String> getCode(Node root) {
        if (root == null) {
            return null;
        }
        getCode(root.left, "0", stringBuilder);
        getCode(root.right, "1", stringBuilder);
        return huffmanMap;
    }

    /**
     * 获取Huffman编码
     *
     * @param node          节点
     * @param code          向左还是向右
     * @param stringBuilder 总
     */
    public static void getCode(Node node, String code, StringBuilder stringBuilder) {

        // TODO: 2022/1/10 必须拼成新的 不影响传入的stringBuilder
        StringBuilder sb = new StringBuilder(stringBuilder);
        sb.append(code);
        if (node != null) {
            // TODO: 2022/1/10 如果节点data为空，则为两个节点之和所创建
            if (node.data == null) {
                getCode(node.left, "0", sb);
                getCode(node.right, "1", sb);
            } else {
                huffmanMap.put(node.data, sb.toString());
            }
        }
    }

    /**
     * 创建huffman树
     *
     * @param nodes
     * @return
     */
    public static Node createHuffmanTree(List<Node> nodes) {
        while (nodes.size() > 1) {
            Collections.sort(nodes);
            Node leftNode = nodes.get(0);
            Node rightNode = nodes.get(1);
            Node parentNode = new Node(null, leftNode.weight + rightNode.weight);
            parentNode.left = leftNode;
            parentNode.right = rightNode;
            nodes.add(parentNode);
            nodes.remove(leftNode);
            nodes.remove(rightNode);
        }

        return nodes.get(0);
    }


    /**
     * 计算单词出现的次数作为权重，并转换成node
     *
     * @param bytes
     */
    public static List<Node> getNodes(byte[] bytes) {

        HashMap<Byte, Integer> counts = new HashMap<Byte, Integer>();
        for (byte abyte : bytes) {
            Integer count = counts.get(abyte);
            if (count == null) {
                counts.put(abyte, 1);
            } else {
                counts.put(abyte, count + 1);
            }
        }
        ArrayList<Node> nodes = new ArrayList<>();
        counts.forEach((k, v) -> {
            nodes.add(new Node(k, v));
        });

        return nodes;
    }

}

class Node implements Comparable<Node> {

    Byte data;
    int weight;
    Node left;
    Node right;

    public Node(Byte date, int weight) {
        this.data = date;
        this.weight = weight;
    }

    @Override
    public String toString() {
        return "Node{" +
                "date=" + data +
                ", weight=" + weight +
                '}';
    }

    @Override
    public int compareTo(Node o) {
        return this.weight - o.weight;
    }

    public void preOrder() {
        System.out.println(this);
        if (this.left != null) {
            this.left.preOrder();
        }
        if (this.right != null) {
            this.right.preOrder();
        }
    }
}
